import sys
import time

from kubernetes import client, config

def init():
    config.load_kube_config(config_file='~/.kube/config')
#     config.load_kube_config(config_file='C:\\Users\\rthac\\.kube\\152.txt')
    v1 = client.CoreV1Api()

    return v1

def get_all_pvc(v1, namespace):
    all_pvc = []
    pvcs = v1.list_namespaced_persistent_volume_claim(namespace)
    for pvc_name in pvcs.items:
        print(pvc_name)
        all_pvc.append(pvc_name.metadata.name)

    return all_pvc

def remove_pvc(namespace):
    v1 = init()
    all_pvc = get_all_pvc(v1, namespace)
    if not all_pvc:
        print("No pvc found.")
        exit(0)

    for pvc in all_pvc:
        v1.delete_namespaced_persistent_volume_claim(pvc, namespace)
    else:
        print("Deleted all pvc found in {}.".format(namespace))

def change_pvc(pvc_namespace, storage_class_name):
    v1 = init()

    while True:
        all_pvc = get_all_pvc(v1, pvc_namespace)
        if not all_pvc:
            time.sleep(60)
            continue

        for pvc_name in all_pvc:
            pvc = v1.read_namespaced_persistent_volume_claim(pvc_name, pvc_namespace)
            pvc.spec.storage_class_name = storage_class_name
            v1.replace_namespaced_persistent_volume_claim(pvc_name, pvc_namespace, pvc)
        else:
            break

def main():
    args = sys.argv[1:]
    if len(args) < 3:
        print('usage: python edit_pvc.py <SUBCOMMAND> <NAMESPACE> <STORAGE_CLASS_NAME>.')
        exit(1)
    subcommand = args[0]
    namespace = args[1]
    storage_class_name = args[2]
    if subcommand == 'remove':
        remove_pvc(namespace)
    elif subcommand == 'change':
        change_pvc(namespace, storage_class_name)



if __name__ == '__main__':
    main()